/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scheduletask;

import dao.FtpInfoCrud;
import dao.ProviderDao;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import pojo.FtpInfo;
import pojo.Provider;

/**
 *
 * @author Mostafa
 */
public class ScheduleTask {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        try 
        {
            String username=args[0];
            String url ="jdbc:mysql://localhost:3306/dimensionproject";
            DriverManager.registerDriver(new com.mysql.jdbc.Driver() );
            Connection c=DriverManager.getConnection(url, "root", "root");
            
            // get provider information and ftp information
            ProviderDao pdao=new ProviderDao(c);
            FtpInfoCrud ftpcrud=new FtpInfoCrud(c);
            Provider p= pdao.getByName(username);
            FtpInfo ftpinfo=ftpcrud.selectById(p.getPId());
            
            //connect to ftp
            String remoteurl=ftpinfo.getRemoteDir()+File.separator+ftpinfo.getFileName()+"."+ftpinfo.getFileExtension();         
            FTPClient client=new FTPClient();
            client.connect(ftpinfo.getHost());
            System.out.println("Connect.......");
            client.login(ftpinfo.getUserName(), ftpinfo.getPassword());
            System.out.println("Log in.......");
            FTPFile[] files= client.listFiles(remoteurl);
            
            //check if file modified
            boolean isgreater=false;
            if(ftpinfo.getDateMod()== null)//||files[0].getTimestamp().getTime().getTime()> ftpinfo.getDateMod().getTime())
             {              
                 File localfile=new File(ftpinfo.getLocalDir()+File.separator+ftpinfo.getFileName()+"."+ftpinfo.getFileExtension());
                 FileOutputStream fos=new FileOutputStream(localfile);
                 client.retrieveFile(remoteurl, fos);  
                 ScriptRunner sr=new ScriptRunner(c, true, false);
                 sr.runScript(new FileReader(p.getScriptPath()),username+"_dim");
            
                 //XML work
                 DocumentBuilderFactory dfactory=DocumentBuilderFactory.newInstance();
                 DocumentBuilder dbuilder=dfactory.newDocumentBuilder();
                 Document xmldocument=dbuilder.parse("src/Configuration/winconfig.xml");
                 Element settingelement=xmldocument.getDocumentElement();
                 Element commonelement=(Element)settingelement.getElementsByTagName("common-path").item(0);
                 Element estimationelement=(Element)settingelement.getElementsByTagName("estimation-path").item(0);
                 String estimationpath=estimationelement.getTextContent();
                 String commonpath=commonelement.getTextContent();
          
                 
                 sr.runScript(new FileReader(commonpath),username+"_dim");
                 sr.runScript(new FileReader(estimationpath),username+"_dim");
               
                 // update modification date of file
                // ftpinfo.setDateMod(new java.sql.Date(files[0].getTimestamp().getTime().getTime()));
                 ftpcrud.update(ftpinfo, ftpinfo.getFtpId());
             }
            
        } 
        catch (SAXException ex) 
        {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (ParserConfigurationException ex) 
        {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (SocketException ex) 
        {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (IOException ex) 
        {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
        } 
        catch (SQLException ex) 
        {
            Logger.getLogger(ScheduleTask.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
